//
//  DetailNewViewController.m
//  yunqiphone
//
//  Created by Maple on 14-3-7.
//  Copyright (c) 2014年 ci123.com. All rights reserved.
//

#import "DetailNewViewController.h"
#import "RCLabel.h"
#import "MWPhotoBrowser.h"
#import "ReplyModel.h"
#import "UserDao.h"
#import "DACircularProgressView.h"
#import <MediaPlayer/MediaPlayer.h>
#import "BaseTableView.h"
#import "UIImageView+WebCache.h"
#import "AFAppClient.h"
#import "MBProgressHUD.h"
#import "Masonry.h"
#import "PopUIManager.h"
#import "NetWorkManager.h"
#import "JsonUtil.h"
#import "Utils.h"
#import "AFAppClient.h"
#import "AppDelegate.h"
#import "Config.h"
#import "MyloginViewController.h"

#define TextViewHeight      170
#define EmojiViewHeight     ((Current_device_vesion < 7.0) ? 165 : 145)
#define PageNum             20
#define HeadViewHeight      130

@interface DetailNewViewController ()
//@property MBProgressHUD *hud;
@property NSString *avatar_header;
@property NSString *preurl;
@end

@implementation DetailNewViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        _replyHeight = 300;
       //- _baseURLString = BBSPostReplyListURLString;
        _page=1;
        currentTag = 0;
        _msgId = @"0";
        _msgNum = @"0";
        _stationInnerId = @"0";
        _isLoadingMore = NO;
        _replyTag = 0;
        _isFromBeauty = NO;
        _isFromPush = NO;
        _replyButtonClickType = 0;
        _replySucc = NO;
    }
    return self;
}
-(void)loadView
{
    UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.view = scrollView;
}
- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    
    [self _initView];
    [self _initBlocks];
    [self _initData];
    [self customView];
}
-(void)customView
{
    if ([self respondsToSelector:@selector(edgesForExtendedLayout)])
        self.edgesForExtendedLayout = UIRectEdgeNone;
    self.navigationController.navigationBarHidden = NO;
    /*
    UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0, 20 , 44, 44)];
    button.showsTouchWhenHighlighted = YES;
    button.backgroundColor = [UIColor clearColor];
    button.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 30);
    [button setImage:[UIImage imageNamed:@"nav_btn_back"] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(backButton:) forControlEvents:UIControlEventTouchUpInside];
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:button];
     */
    [self CustomBackButton];
   /*
    UIBarButtonItem *backButton = [[UIBarButtonItem alloc]
                                   initWithTitle:@""
                                   style:UIBarButtonItemStylePlain
                                   target:nil
                                   action:nil];
    self.navigationItem.backBarButtonItem=backButton;
    */
    
    self.navigationItem.title = @"话题详情";
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapView)];
    self.view.userInteractionEnabled = YES;
    [self.view addGestureRecognizer:tap];
    
}
-(void)backButton:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}
-(void)tapView
{
    [self.view endEditing:YES];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
  /*  [NOTIFICATION_CENTER addObserver:self
                            selector:@selector(keyboardWillShow:)
                                name:UIKeyboardWillShowNotification
                              object:nil];
    [NOTIFICATION_CENTER addObserver:self
                            selector:@selector(keyboardWillHide:)
                                name:UIKeyboardWillHideNotification
                              object:nil];
   */
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    /*
    [NOTIFICATION_CENTER removeObserver:self
                                   name:UIKeyboardWillShowNotification
                                 object:nil];
    [NOTIFICATION_CENTER removeObserver:self
                                   name:UIKeyboardWillHideNotification
                                 object:nil];
     */
}

#pragma mark - UI

- (void)_initView {
    
    _HomeUserInfo = [[UserDao getInstance] getUserInfo];
    
    _tableView = [[ReplyTableView alloc]initWithFrame:CGRectMake(0, 0, APP_SCREEN_WIDTH, APP_SCREEN_HEIGHT-((AppDelegate*)[UIApplication sharedApplication].delegate).Status_Gap-CUSTOM_NAV_HEIGHT) style:UITableViewStylePlain];
    [_tableView setBackgroundView:nil];
    _indicatorView = [[IndicatorView alloc] initWithFrame:CGRectMake(0, HeadViewHeight - 40, APP_SCREEN_WIDTH, APP_SCREEN_HEIGHT - HeadViewHeight - 50)];
    [_indicatorView setIndicatorDelegate:self];
    [_tableView addSubview:_indicatorView];
    
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.backgroundColor = RGBCOLOR(255, 255, 255);
    _tableView.egoFreshDelegate = self;
    _tableView.isheaderView = NO;//是否添加刷新
    [_tableView setAllowsSelection:NO];
    [self.view addSubview:_tableView];
    
    _scrollView=[[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, APP_SCREEN_WIDTH,HeadViewHeight)];
    _scrollView.backgroundColor=[UIColor whiteColor];
    _scrollView.scrollsToTop = NO;
    [self _initHeadView];
    _tableView.tableHeaderView=_scrollView;
    
    _picArr=[[NSMutableArray alloc]init];
    
    [self showReplyView:NO];
    [_tableView bringSubviewToFront:_indicatorView];
    [_tableView bringSubviewToFront:_tableView.tableHeaderView];
}


- (void)_initHeadView {
    _headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, APP_SCREEN_WIDTH, HeadViewHeight)];
    [_scrollView addSubview:_headView];

    NSString *title=@"人家正在获取数据中啦。。。";

    //初始化label
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(15,0,APP_SCREEN_WIDTH - 10,50)];
    //设置自动行数与字符换行
    [titleLabel setNumberOfLines:0];
    titleLabel.lineBreakMode = NSLineBreakByTruncatingTail;
    titleLabel.text = title;
    titleLabel.textColor=RGBCOLOR(97, 97, 97);
    titleLabel.tag = 100;
    titleLabel.font = [UIFont fontWithName:@"Arial" size:20];
    titleLabel.backgroundColor=[UIColor clearColor];
    
    
    
    _headImage = [[UIImageView alloc] initWithFrame:CGRectMake(10, titleLabel.bottom+25, 50, 50)];
    _headImage.image=[UIImage imageNamed:@"default_avatar"];
    _headImage.tag=101;
    _headImage.layer.cornerRadius = 25;
    _headImage.layer.masksToBounds = YES;
    _headImage.userInteractionEnabled=YES;



    UILabel *nick=[[UILabel alloc] initWithFrame:CGRectMake(_headImage.right + 11, _headImage.top + 18, 90, 16)];
    nick.text=@"";
    nick.textColor = UIColorMake(144, 144, 144);
    nick.tag=102;
    nick.font=[UIFont systemFontOfSize:15];
    nick.backgroundColor=[UIColor clearColor];
    nick.userInteractionEnabled = YES;



    UILabel *tips=[[UILabel alloc] initWithFrame:CGRectMake(APP_SCREEN_WIDTH-50, _headImage.top + 18, 90, 16)];
    tips.text=@"楼主";
    tips.textColor = UIColorMake(177, 177, 177);
    tips.tag=103;
    tips.font=[UIFont systemFontOfSize:15];
    tips.backgroundColor=[UIColor clearColor];

    
    UILabel *time=[[UILabel alloc] initWithFrame:CGRectMake(APP_SCREEN_WIDTH - 100 + 12 + 3.5, _headImage.top , 80, 22)];
    time.text=@"";
    time.tag=104;
    [time setAdjustsFontSizeToFitWidth:YES];
    time.font=[UIFont systemFontOfSize:15];
    time.textColor = RGBCOLOR(150, 150, 150);
    time.backgroundColor = [UIColor clearColor];

    if(_postData!=nil){
        titleLabel.textColor = RGBCOLOR(197, 166, 122);
        titleLabel.text=[NSString stringWithFormat:@"%@",_postData[@"title"]];
        if (titleLabel.text.length > 18) {
            titleLabel.font = [UIFont fontWithName:@"Arial" size:18];
        }
        nick.text=[NSString stringWithFormat:@"%@",_postData[@"nick"]];
        time.text=[NSString stringWithFormat:@"%@",_postData[@"time"]];
      //  labelReplyNum.text=[NSString stringWithFormat:@"%@",_postData[@"replyNum"]];
        [_headImage sd_setImageWithURL:[NSURL URLWithString:_postData[@"head"]] placeholderImage:[UIImage imageNamed:@"default_avatar"]];
    }
    /*
    CALayer *bottomBorder = [CALayer layer];
    bottomBorder.frame = CGRectMake(0.0f, titleLabel.bottom + 18, _headView.width, 0.5f);
    bottomBorder.backgroundColor = RGBCOLOR(224, 224, 224).CGColor;
    [_headView.layer addSublayer:bottomBorder];
     */
    
    [_headView addSubview:_headImage];
    [_headView addSubview:nick];
     //  [_headView addSubview:time];
    [_headView addSubview:tips];
    [_headView addSubview:titleLabel];
}

-(void)_initContentView
{
    _height_total = 10;
    int imageTag = 100;
    int progresstag = 200;

    _goUrldata = [NSMutableArray arrayWithCapacity:10];

    _contentView = [[UIView alloc] initWithFrame:CGRectMake(0, _headView.bottom, APP_SCREEN_WIDTH, 0)];
    _contentView.backgroundColor = [UIColor whiteColor];
    [_scrollView addSubview:_contentView];

    //停止活动指示器
    [_indicatorView setHidden:YES];

    NSMutableArray *tmpPics = [[NSMutableArray alloc]init];
    
    NSString *text=[NSString stringWithFormat:@"%@",_contentData[@"content"]];
    
    text = [NSString stringWithFormat:@"%@", text];
   
     RCLabelComponentsStructure *componentsDS = [RCLabel extractTextStyle:text];
    
    RCLabel *tempLabel = [[RCLabel alloc] initWithFrame:CGRectMake(10, _height_total, APP_SCREEN_WIDTH - 20, 100)];
    tempLabel.textColor = RGBCOLOR(109, 97, 83);
    tempLabel.componentsAndPlainText = componentsDS;
//    tempLabel.delegate = self;
    tempLabel.lineSpacing = 10;
    tempLabel.tag = 0;
    
    CGSize optimalSize = [tempLabel optimumSize:YES];
    tempLabel.frame = CGRectMake(10, _height_total, tempLabel.width, optimalSize.height);
    _height_total += optimalSize.height+15;
    [_contentView addSubview:tempLabel];
    for(int i=0; i<_picArr.count;i++){
        NSMutableDictionary *infoDic=[_picArr objectAtIndex:i];
            NSString *picUrl;
        
            picUrl = [NSString stringWithFormat:@"%@%@", _avatar_header,[infoDic objectForKey:@"srcurl"]];
        

            int reW = [[NSString stringWithFormat:@"%@", infoDic[@"width"]] intValue];
            int reH = [[NSString stringWithFormat:@"%@", infoDic[@"height"]] intValue];

            CGFloat fullWidth = APP_SCREEN_WIDTH - 20;
            float pic_w = fullWidth;
            float pic_h = fullWidth;
            if(picUrl != nil && [picUrl rangeOfString:@"/emotion/"].location != NSNotFound){
                pic_w = 24;
                pic_h = 24;
            }else if ((0 < reW && reW < 50) || (0< reH && reH < 50)) {
                pic_w = reW > 0 ? reW : 24;
                pic_h = reH > 0 ? reH : 24;
            }else if(reW != 0 && reH != 0){
                pic_h = (int)(pic_w * reH / reW);
            }
            
            UIImageView *image=[[UIImageView alloc] initWithFrame:CGRectMake((APP_SCREEN_WIDTH - pic_w) / 2, _height_total, pic_w, pic_h)];
            UIImageView *progressimage = [[UIImageView alloc] initWithFrame:CGRectMake((APP_SCREEN_WIDTH - pic_w) / 2, _height_total, pic_w, pic_h)];
            
            _height_total += pic_h + 15;
            
            progressimage.image = [UIImage imageNamed:@"detail_picloading_bg"];
            progressimage.tag = imageTag;
            DACircularProgressView *progressView = [[DACircularProgressView alloc] initWithFrame:CGRectMake((progressimage.width - 60)/2, (progressimage.height-60)/2, 60.0f, 60.0f)];
            progressView.roundedCorners = YES;
            progressView.trackTintColor = [UIColor grayColor];
            progressView.thicknessRatio = 0.25f;
            progressView.tag = progresstag;
            progresstag++;
            
            [image sd_setImageWithURL:[NSURL URLWithString:picUrl] placeholderImage:[UIImage imageNamed:@"detail_picloading_bg"] options:SDWebImageProgressiveDownload
                          progress:^(NSInteger receivedSize, NSInteger expectedSize) {
                              progressView.hidden=NO;
                              double progress= ((double)receivedSize/expectedSize);
                              [progressView setProgress:progress animated:YES];
                          }completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
                              progressView.hidden=YES;
                              progressimage.hidden=YES;
                          }];
            [image setBackgroundColor:[UIColor whiteColor]];
            image.tag = imageTag;
            imageTag++;
            image.contentMode = UIViewContentModeScaleAspectFill;
            image.userInteractionEnabled = YES;
            [image.layer setMasksToBounds:YES];
            UITapGestureRecognizer *ges=[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(showImages:)];
            [image addGestureRecognizer:ges];
            [_contentView addSubview:image];
            [progressimage addSubview:progressView];
            [_contentView addSubview:progressimage];

            //获取图片
            NSString *bigUrl = [NSString stringWithFormat:@"%@%@", _avatar_header,[infoDic objectForKey:@"srcurl"]];
            [tmpPics addObject:[MWPhoto photoWithURL:[NSURL URLWithString:bigUrl]]];
        
    }
    
    _picArray = tmpPics;

    _height_total += 20;
    _actionView = [[UIView alloc]initWithFrame:CGRectMake(0, _height_total, APP_SCREEN_WIDTH, 0)];
   
    int actionHeight = 20 ;

    UILabel *time=[[UILabel alloc] initWithFrame:CGRectMake(30, actionHeight-25, 200, 22)];
    time.tag=104;
    //[time setAdjustsFontSizeToFitWidth:YES];
    time.font=[UIFont systemFontOfSize:12];
    time.textColor = RGBCOLOR(150, 150, 150);
    time.backgroundColor = [UIColor clearColor];
    [_actionView addSubview:time];
    time.text=[NSString stringWithFormat:@"%@",_contentData[@"post_time"]];
    
    UIImageView *timeImage = [[UIImageView alloc]initWithFrame:CGRectMake(8, actionHeight-24, 26, 20)];
    [timeImage setImage:[UIImage imageNamed:@"lock"]];
    [timeImage setBackgroundColor:[UIColor clearColor]];
    [_actionView addSubview:timeImage];
    
    
    UIImageView *iconReplyNum = [[UIImageView alloc] initWithFrame:CGRectMake(APP_SCREEN_WIDTH - 50, actionHeight-22, 22, 14)];
    [iconReplyNum setBackgroundColor:[UIColor clearColor]];
    [iconReplyNum setImage:[UIImage imageNamed:@"comment_gray"]];
    [_actionView addSubview:iconReplyNum];
    
    UILabel *labelReplyNum = [[UILabel alloc] initWithFrame:CGRectMake(iconReplyNum.right + 3, iconReplyNum.top, 35, 13)];
    [labelReplyNum setBackgroundColor:[UIColor clearColor]];
    [labelReplyNum setText:@"0"];
    [labelReplyNum setTag:106];
    [labelReplyNum setFont:[UIFont systemFontOfSize:12.0f]];
    [labelReplyNum setTextColor:RGBCOLOR(97, 97, 97)];
    
     NSInteger replyCount = _contentData[@"replynum"] ? [_contentData[@"replynum"] integerValue] : 0;
    
    labelReplyNum.text = [NSString stringWithFormat:@"%ld",(long)replyCount];
    [_actionView addSubview:labelReplyNum];
    //     UILabel *replyNum = (UILabel *)[_headView viewWithTag:106];
    //    [replyNum setText:[NSString stringWithFormat:@"%ld", (long)replyCount]];


  
    UIButton *reply=[[UIButton alloc] initWithFrame:CGRectMake(APP_SCREEN_WIDTH-75, actionHeight - 24, 60, 24)];
    
    [reply setTitle:@"回复" forState:UIControlStateNormal];
    [reply setImage:[UIImage imageNamed:@"comment_blue"] forState:UIControlStateNormal];
    [reply setTitleColor:UIColorMake(120, 165, 212) forState:UIControlStateNormal];
    [reply addTarget:self action:@selector(replyAction2:) forControlEvents:UIControlEventTouchUpInside];
    reply.titleLabel.font = [UIFont systemFontOfSize:14];
    
    //[_actionView addSubview:reply];
   
    actionHeight += 15;
    

    _actionView.height = actionHeight;
    
    [_contentView addSubview:_actionView];
    _contentView.height = _height_total + _actionView.height;

    _scrollView.contentSize=CGSizeMake(320, _contentView.bottom);
    _scrollView.height=_contentView.bottom;
    _tableView.tableHeaderView=_scrollView;

    [self refreshTable];
    
    CALayer *borderBottom = [CALayer layer];
    [borderBottom setBackgroundColor:DefaultViewBackgroundColor.CGColor];
    [borderBottom setFrame:CGRectMake(0, _scrollView.height - 4, _scrollView.width, 4)];
    [_scrollView.layer addSublayer:borderBottom];
}


-(void)refreshTable
{
    _tableView.pageNum = PageNum;
    _tableView.data = _data;
    [_tableView reloadData];
    [_tableView doneLoadingTableViewData];

    [self showReplyView:YES];

    
    if (![_msgId isEqualToString:@"0"]) {
       // [self scrollToReply];
    }
    
    if (_data.count <= 0) {
        _noReplyTip = [[UILabel alloc] initWithFrame:CGRectMake(0, _scrollView.height, APP_SCREEN_WIDTH, 40)];
        [_noReplyTip setBackgroundColor:[UIColor clearColor]];
        [_noReplyTip setFont:[UIFont systemFontOfSize:14.0f]];
        [_noReplyTip setText:@"暂时还没有回帖哦~"];
        [_noReplyTip setTextColor:RGBCOLOR(109, 97, 83)];
        [_noReplyTip setTextAlignment:NSTextAlignmentCenter];
        [_tableView addSubview:_noReplyTip];
        [_tableView bringSubviewToFront:_noReplyTip];
    }
}

#pragma mark - Data

-(void)_initData
{
    NSMutableDictionary *params = [[NSMutableDictionary alloc]init];
    if (![_msgId isEqualToString:@"0"]) {
       // [params setObject:@([[UserDao getInstance]getUserId]) forKey:@"uid"];
        [params setObject:_msgId forKey:@"postid"];
    }
    
    PopUIManager *popUIMgr = [PopUIManager getInstanse];
    
    [[AFAppClient sharedManager]getWithURL:[NSString stringWithFormat:@"%@%@",SERVER_URL_NEW,API_USER_GET_POST_BY_ID] withParameters:params success:^(NSDictionary* dict) {
        
        if ([dict[@"retCode"] isEqualToNumber:@10020]) {
            UILabel *title = (UILabel *)[self.headView viewWithTag:100];
            title.text = @"很抱歉，此帖已被删除！";
            title.textColor = RGBCOLOR(255, 102, 102);
            
            return;
        }else if ([[dict objectForKey:@"ret"] integerValue]== 1) {
            self.contentData = dict[@"post"];
            self.picArr = dict[@"post"][@"pics"];
            self.tableView.replyTotal = [dict[@"post"][@"replynum"]integerValue];
            self.avatar_header = dict[@"avatar_header"];
            self.preurl = dict[@"preurl"];
            self.tableView.isAscending = YES;
            [self _initHeadViewData];
        }else{
            [popUIMgr popAlertView:nil title:@"提示" message:@"数据解析错误" cancelButtonTitle:@"确定"];
        }
        [self requestReplyData];
    } failure:^(NSError *error) {
        NSLog(@"Http Error: %@   %ld", error.localizedDescription,(long)error.code);
        NSString *error_content = [NSString stringWithFormat:@"连接错误:%ld",(long)error.code];
        [popUIMgr popAlertView:nil title:@"提示" message:error_content cancelButtonTitle:@"确定"];
    }];
}

-(void)_initHeadViewData
{
    UILabel *title=(UILabel *)[_headView viewWithTag:100];
    title.text=[NSString stringWithFormat:@"%@",_contentData[@"title"]];
    
    UILabel *nick = (UILabel *)[_headView viewWithTag:102];
    nick.text=[NSString stringWithFormat:@"%@",_contentData[@"author_name"]];
    CGSize size = [nick.text sizeWithFont:nick.font constrainedToSize:nick.size lineBreakMode:NSLineBreakByWordWrapping];
    
    float marginLeft;
    if (size.width < nick.width) {
        [nick setWidth:size.width];
        marginLeft = nick.right + 8;
    }else {
        marginLeft = nick.right;
    }
    

    [_headImage sd_setImageWithURL:[NSURL URLWithString:_contentData[@"author_avatar"]] placeholderImage:_headImage.image];
    
//    NSInteger replyCount = _contentData[@"replynum"] ? [_contentData[@"replynum"] integerValue] : 0;
    
//     UILabel *replyNum = (UILabel *)[_headView viewWithTag:106];
//    [replyNum setText:[NSString stringWithFormat:@"%ld", (long)replyCount]];
}

-(void)requestReplyData
{
    _page = 1;
    NSDictionary *params;
    params = @{
               @"postid":_msgId,
               @"dir":@"new"
               };
     PopUIManager *popUIMgr = [PopUIManager getInstanse];
     [[AFAppClient sharedManager]getWithURL:[NSString stringWithFormat:@"%@%@",SERVER_URL_NEW,API_USER_GET_REPLYS] withParameters:params success:^(NSDictionary *dict) {
         if ([[dict objectForKey:@"ret"] integerValue]== 1) {
             [self.data removeAllObjects];
             
             self.data = [NSMutableArray arrayWithCapacity:[dict[@"replys"] count]];
             _tableView.avatar_header = [dict objectForKey:@"avatar_header"];
             
             for(NSDictionary *dic in dict[@"replys"]) {
                 ReplyModel *list = [[ReplyModel alloc] initWithDataDic:dic];
                 if (list != nil) {
                     [self.data addObject:list];
                 }
             }
             if(_replySucc){
                 self.tableView.data = self.data;
                 [self.tableView reloadData];
                 [self.tableView doneLoadingTableViewData];
                 [self scrollToReply];
                 [self refreshReplyNum];
                 _replySucc = NO;
             }else{
                 [self _initContentView];
             }
             
             
         }else{
             [popUIMgr popAlertView:nil title:@"提示" message:@"数据解析错误" cancelButtonTitle:@"确定"];
         }
    } failure:^(NSError *error) {
        NSLog(@"Http Error: %@   %ld", error.localizedDescription,(long)error.code);
        NSString *error_content = [NSString stringWithFormat:@"连接错误:%ld",(long)error.code];
        [popUIMgr popAlertView:nil title:@"提示" message:error_content cancelButtonTitle:@"确定"];
    }];
}

#pragma mark - AFNetworking Block

- (void)_initBlocks
{
    __weak typeof (self) weakSelf = self;
    
    self.blockGetPostDetailSuccess = ^(NSDictionary *response){
        __strong typeof (weakSelf) strongSelf = weakSelf;
        if (!strongSelf) {
            return;
        }
        
        if([response[@"ret"]integerValue] == 1){
            if ([response[@"retCode"] isEqualToNumber:@10020]) {
                UILabel *title = (UILabel *)[strongSelf.headView viewWithTag:100];
                title.text = @"很抱歉，此帖已被删除！";
                title.textColor = RGBCOLOR(255, 102, 102);
                [strongSelf.indicatorView setHidden:YES];
                return;
            }else if([response[@"retCode"] isEqualToNumber:@1]){
                strongSelf.contentData = response[@"post"];
                strongSelf.picArr = response[@"post"][@"pics"];
                strongSelf.tableView.replyTotal = [response[@"post"][@"replynum"]integerValue];
                strongSelf.avatar_header = response[@"avatar_header"];
                strongSelf.preurl = response[@"preurl"];
                strongSelf.tableView.isAscending = YES;
                
            }else{
                [strongSelf ShowExclaHud:@"网络不给力，请检查网络！"];
            }

        }

    };
    
    self.blockChangeReplyListSuccess = ^(NSDictionary *response){
        __strong typeof (weakSelf) strongSelf = weakSelf;
        if (!strongSelf) {
            return;
        }
        
        if([response[@"retCode"] integerValue] == 1){
            
            [strongSelf.data removeAllObjects];
          
        
            strongSelf.data = [NSMutableArray arrayWithCapacity:[response[@"replys"] count]];
            
            for(NSDictionary *dic in response[@"replys"]) {
                ReplyModel *list = [[ReplyModel alloc] initWithDataDic:dic];
                if (list != nil) {
                    [strongSelf.data addObject:list];
                }
            }
            
            [strongSelf _initHeadViewData];
            [strongSelf _initContentView];
            
            if (![strongSelf.msgId isEqualToString:@"0"]) {
                strongSelf.page = 0;
                strongSelf.tableView.needAutoModifiedByData = NO;
                strongSelf.tableView.isAutoload = NO;
                strongSelf.tableView.isfooterView = YES;
                strongSelf.tableView.pageNum = strongSelf.data.count;
            }

        }
       
    };
    
    self.blockLoadMoreSuccess = ^(NSDictionary *response){
        __strong typeof (weakSelf) strongSelf = weakSelf;
        if (!strongSelf) {
            return;
        }
        
        strongSelf.page += 1;
        NSMutableArray *tmpArray = [NSMutableArray arrayWithCapacity:[response[@"data"] count]];
        for(NSDictionary *dic in response[@"data"]) {
            ReplyModel *list = [[ReplyModel alloc] initWithDataDic:dic];
            if (list) {
                [tmpArray addObject:list];
            }
        }
        [strongSelf.data addObjectsFromArray:tmpArray];
        if ([tmpArray count] < 20) {
            strongSelf.tableView.isfooterView = NO;
        }
        [strongSelf.tableView doneLoadingMore:NO];
        
        strongSelf.tableView.needAutoModifiedByData = YES;
        strongSelf.tableView.data = strongSelf.data;
        strongSelf.tableView.pageNum = PageNum;
        [strongSelf.tableView reloadData];
        [strongSelf.tableView doneLoadingTableViewData];
        strongSelf.isLoadingMore = NO;
    };
    
    
    self.blockPubReplySuccess = ^(NSDictionary *response){
        __strong typeof (weakSelf) strongSelf = weakSelf;
        if (!strongSelf) {
            return;
        }
        
       [strongSelf showHudComplete:@"回复成功" success:YES];
    
        
        if([response[@"retCode"] isEqualToNumber:@1]) {
            NSDictionary *dic = response[@"rdata"];
            ReplyModel *list = [[ReplyModel alloc] initWithDataDic:dic];
            if (!strongSelf.isQuoteReply) {
                if (list != nil) {
                    [strongSelf showHudComplete:@"回复成功" success:YES];
                    [strongSelf requestReplyData];
                    _replySucc = YES;
                }else {
                    [strongSelf showHudComplete:@"回复失败" success:NO];
                }
            }else {
                if (list != nil) {
                    int pos = -1;
                    for (int i = 0; i < strongSelf.data.count; i++) {
                        ReplyModel *reply = strongSelf.data[i];
                        if ([reply.replyId integerValue] == strongSelf.replyTag) {
                            pos = i;
                            break;
                        }
                    }

                    if (pos >= 0) {
                        [strongSelf.data[pos] setReplyQuoteUid:[NSNumber numberWithInteger:[list.replyUserId integerValue]]];
                        if (list.replyUserPic.length > 0) {
                            [strongSelf.data[pos] setReplyQuoteContent:[NSString stringWithFormat:@"%@%@", list.replyContent, @"（图片已回复成功）"]];
                        }else {
                            [strongSelf.data[pos] setReplyQuoteContent:list.replyContent];
                        }
                        [strongSelf.data[pos] setReplyQuoteNick:list.replyUserNick];
                    }
                    strongSelf.tableView.replyTotal++;
                    strongSelf.tableView.data = strongSelf.data;
                    [strongSelf.tableView reloadData];
                    [strongSelf.tableView doneLoadingTableViewData];
                    
                    [strongSelf refreshReplyNum];
                }
            }
        }else {
            [strongSelf showHudComplete:@"回复失败" success:NO];
            if (response[@"msg_id"]) {
                [strongSelf ShowExclaHud:[NSString stringWithFormat:@"错误码：%@", response[@"msg_id"]]];
            }
        }
    };
    
}

#pragma mark - MWPhotoBrowserDelegate
- (NSUInteger)numberOfPhotosInPhotoBrowser:(MWPhotoBrowser *)photoBrowser {
  return _picArray.count;
}

- (MWPhoto *)photoBrowser:(MWPhotoBrowser *)photoBrowser photoAtIndex:(NSUInteger)index {
  if (index < _picArray.count)
    return [_picArray objectAtIndex:index];
  return nil;
}

- (MWPhoto *)photoBrowser:(MWPhotoBrowser *)photoBrowser thumbPhotoAtIndex:(NSUInteger)index {
    if (index < _picArray.count)
        return [_picArray objectAtIndex:index];
    return nil;
}

#pragma mark - EGORefreshTableHeaderDelegate

- (void)loadMore:(BaseTableView *)base{
    if (_isLoadingMore) {
        return;
    }

    if(_data.count > 0){
        NSDictionary *params;
        
        ReplyModel *dict = [_data lastObject];
        NSString *post_id = dict.replyPostId;
        
        params = @{
            @"uid":@([[UserDao getInstance]getUserId]),
            @"token":[[UserDao getInstance]getAccessToken],
            @"utype":@(1),
            @"postid":_msgId,
            @"dir":@"old",
            @"baseid":post_id
        };

        NSString *dataString = [JsonUtil convertDictionaryToJson:params];
        
        PopUIManager *popUIMgr = [PopUIManager getInstanse];
        [[NetWorkManager getInstanse] requestURLAsynMessage:USER_GET_REPLYS data:dataString FinishBlock:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
            self.isLoadingMore = NO;
            if (connectionError) { //连接失败
                NSLog(@"Http Error: %@   %ld", connectionError.localizedDescription,(long)connectionError.code);
                NSString *error_content = [NSString stringWithFormat:@"连接错误:%ld",(long)connectionError.code];
                [popUIMgr popAlertView:nil title:@"提示" message:error_content cancelButtonTitle:@"确定"];
            }else{//连接成功，判断是否有数据返回
                if (data) {
                    NSDictionary *dict = [JsonUtil convertDataToDictionary:data];
                    if ([[dict objectForKey:@"ret"] integerValue]== 1) {
                        self.page += 1;
                        NSMutableArray *tmpArray = [NSMutableArray arrayWithCapacity:[dict[@"replys"] count]];
                        for(NSDictionary *dic in dict[@"replys"]) {
                            ReplyModel *list = [[ReplyModel alloc] initWithDataDic:dic];
                            if (list) {
                                [tmpArray addObject:list];
                            }
                        }
                        [self.data addObjectsFromArray:tmpArray];
                        if ([tmpArray count] < 20) {
                            self.tableView.isfooterView = NO;
                        }
                        [self.tableView doneLoadingMore:NO];
                        
                        self.tableView.needAutoModifiedByData = YES;
                        self.tableView.data = self.data;
                        self.tableView.pageNum = PageNum;
                        [self.tableView reloadData];
                        [self.tableView doneLoadingTableViewData];
                        
                    }else{
                        [popUIMgr popAlertView:nil title:@"提示" message:@"数据解析错误" cancelButtonTitle:@"确定"];
                    }
                }else{
                    [popUIMgr popAlertView:nil title:@"提示" message:@"服务器没有返回数据" cancelButtonTitle:@"确定"];
                }
            }
        }];

        _isLoadingMore = YES;
    }else{
        [_tableView doneLoadingMore:YES];
    }
}

- (void)tableView:(BaseTableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
  UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
  [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
}

-(void)getReplyBox:(UITapGestureRecognizer *)ges
{
    _replyTag = ges.view.tag;
    NSString *replyId;
    NSString *nick;
    NSString *replyFloor;
    for (ReplyModel *reply in _data) {
        if ([reply.replyId integerValue] == _replyTag) {
            replyId = reply.replyId;
            nick = reply.replyUserNick;
            break;
        }
    }

    if (replyId <= 0) {
        return;
    }
    
    _replyId = [NSString stringWithFormat:@"%@",replyId];
    _replyFloor = [NSString stringWithFormat:@"%@", replyFloor];

    //[self replyAction:nil];
    [_textFiled becomeFirstResponder];
    _replyName.text = [NSString stringWithFormat:@"回复：%@",[nick stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
}

//回复框
#pragma mark - Private Methods

- (void)showReplyView:(BOOL)show {
    if(_replyView == nil) {
        _replyView = [[UIView alloc] initWithFrame:CGRectMake(0, APP_SCREEN_HEIGHT - 64, APP_SCREEN_WIDTH, 49)];
        _replyView.backgroundColor = RGBCOLOR(239, 239, 239);
        _replyView.userInteractionEnabled = YES;

        CALayer *topBorder = [CALayer layer];
        [topBorder setBackgroundColor:RGBCOLOR(186, 186, 186).CGColor];
        [topBorder setFrame:CGRectMake(0, 0, _replyView.width, 0.5)];
        [[_replyView layer] addSublayer:topBorder];

        
      //  UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(replyAction:)];
      //  [boxView addGestureRecognizer:tap];

        _replyImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"camara_little"]];
        _replyImage.backgroundColor = [UIColor clearColor];
        _replyImage.frame = CGRectMake(5, 12, 26, 20);
        [_replyView addSubview:_replyImage];
        _replyImage.userInteractionEnabled =YES;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(selectImageFromPhone)];
         [_replyImage addGestureRecognizer:tap];
        
        UIView *boxView = [[UIView alloc] initWithFrame:CGRectMake(35, 7, APP_SCREEN_WIDTH - 30 - 70, 33)];
        boxView.backgroundColor = [UIColor whiteColor];
        boxView.layer.borderWidth = 0.5;
        boxView.layer.borderColor = RGBCOLOR(206, 206, 206).CGColor;
        boxView.layer.cornerRadius = 5.0f;
        boxView.layer.masksToBounds = YES;

         _textFiled = [[UITextField alloc] init];
        _textFiled.textAlignment = NSTextAlignmentLeft;
        _textFiled.backgroundColor = [UIColor clearColor];
        _textFiled.font = [UIFont systemFontOfSize:14];
        _textFiled.textColor = RGBCOLOR(97, 97, 97);
        _textFiled.placeholder = @"";
        [boxView addSubview:_textFiled];
        [_replyView addSubview:boxView];
        
        [_textFiled mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.equalTo(APP_SCREEN_WIDTH - 30 - 70-10);
            make.height.equalTo(25);
            make.centerX.equalTo(_replyView.mas_centerX).offset(-15);
            make.centerY.equalTo(_replyView.mas_centerY);
        }];
        
        _postReply = [[UIButton alloc] initWithFrame:CGRectMake(APP_SCREEN_WIDTH-63, 8,  60, 30)];
        _postReply.backgroundColor = UIColorMake(252, 74, 74);
        [_postReply setTitle:@"发送" forState:UIControlStateNormal];
        [_postReply setTintColor:[UIColor whiteColor]];
        _postReply.layer.cornerRadius = 5.0f;
        _postReply.layer.masksToBounds = YES;
        [_replyView addSubview:_postReply];
        [_postReply addTarget:self action:@selector(postReply) forControlEvents:UIControlEventTouchUpInside];
        

        [self.view addSubview:_replyView];
    }

    if(show) {
        _replyView.hidden = NO;
        [UIView animateWithDuration:0.5 animations:^{
            _replyView.top = APP_SCREEN_HEIGHT-49 - 64;
        }];
    }else {
        [UIView animateWithDuration:0.1
                         animations:^{
                             _replyView.top = APP_SCREEN_HEIGHT-64;
                         }
                         completion:^(BOOL finish){
                             if(finish) {
                                 _replyView.top = APP_SCREEN_HEIGHT-64;
                                 _replyView.hidden = YES;
                             }
                         }];
    }
}

-(void)replyAction2:(id)sender
{
   // [self showContentView:YES];
    [_textFiled becomeFirstResponder];
}
//回复
- (void)replyAction:(id)sender
{
    if([sender isKindOfClass:[UIButton class]]) {
        _isQuoteReply = NO;
        
    }else if([sender isKindOfClass:[UITapGestureRecognizer class]]){
        _isQuoteReply = NO;
        
    }else if( sender == nil){
        _isQuoteReply = YES;
    }

    [self showContentView:YES];
}

- (void)showContentView:(BOOL)show {
   // UIWindow *window = [[UIApplication sharedApplication]keyWindow];
    if(_replyContentView == nil) {
        _replyContentView = [[UIView alloc] initWithFrame:CGRectMake(0, APP_SCREEN_HEIGHT-64, APP_SCREEN_WIDTH, TextViewHeight)];
        _replyContentView.backgroundColor = RGBCOLOR(250, 250, 250);

        CALayer *topBorder = [CALayer layer];
        [topBorder setBackgroundColor:RGBCOLOR(186, 186, 186).CGColor];
        [topBorder setFrame:CGRectMake(0, 0, _replyContentView.width, 0.5)];
        [[_replyContentView layer] addSublayer:topBorder];
        
        //回复栏
        _textView = [[UITextView alloc] initWithFrame:CGRectMake(15, 42, APP_SCREEN_WIDTH - 30, 90)];
        _textView.backgroundColor = [UIColor whiteColor];
        [[_textView layer] setCornerRadius:5.0f];
        [[_textView layer] setMasksToBounds:YES];
        [[_textView layer] setBorderColor:RGBCOLOR(186, 186, 186).CGColor];
        [[_textView layer] setBorderWidth:0.5f];
        _textView.font = [UIFont systemFontOfSize:15];
        _textView.delegate = self;
        [_replyContentView addSubview:_textView];

        //回复谁
        _replyName = [[UILabel alloc] initWithFrame:CGRectMake(60, 13, APP_SCREEN_WIDTH - 120, 16)];
        _replyName.backgroundColor = [UIColor clearColor];
        _replyName.font = [UIFont systemFontOfSize:16];
        _replyName.text = @"回复";
        _replyName.textAlignment = NSTextAlignmentCenter;
        [_replyContentView addSubview:_replyName];

        _cancelButton = [[UIButton alloc] initWithFrame:CGRectMake(15, 13, 50, 16)];
        _cancelButton.titleLabel.font = [UIFont systemFontOfSize:16];
        [_cancelButton setBackgroundColor:[UIColor clearColor]];
        [_cancelButton setTitle:@"取消" forState:UIControlStateNormal];
        [_cancelButton setTitleColor:RGBCOLOR(255, 83, 123) forState:UIControlStateNormal];
        [_cancelButton setShowsTouchWhenHighlighted:YES];
        [_cancelButton addTarget:self action:@selector(hideContentView) forControlEvents:UIControlEventTouchUpInside];
        [_replyContentView addSubview:_cancelButton];

        //发送
        _postReply = [UIButton buttonWithType:UIButtonTypeCustom];
        _postReply.frame = CGRectMake(APP_SCREEN_WIDTH - 50 - 15, 7, 50, 27);
        _postReply.titleLabel.font = [UIFont systemFontOfSize:14];
        [_postReply setShowsTouchWhenHighlighted:YES];
        [_postReply setBackgroundImage:[UIImage imageNamed:@"detail_btn_pub"] forState:UIControlStateNormal];
        [_postReply setEnabled:NO];
        [_postReply addTarget:self action:@selector(postReply) forControlEvents:UIControlEventTouchUpInside];
        [_replyContentView addSubview:_postReply];
        
        _replyPicBtb=[[UIButton alloc] initWithFrame:CGRectMake(APP_SCREEN_WIDTH - 54 - 10, _textView.bottom, 54, 40)];
        [_replyPicBtb setBackgroundImage:[UIImage imageNamed:@"pub_btn_camera"] forState:UIControlStateNormal];
        [_replyPicBtb addTarget:self action:@selector(selectImageFromPhone) forControlEvents:UIControlEventTouchUpInside];
        [_replyContentView addSubview:_replyPicBtb];
        

        _replyImage=[[UIImageView alloc] initWithFrame:CGRectMake(_textView.left, _textView.bottom+4, 30, 30)];
        [_replyContentView addSubview:_replyImage];


        UIView *tap = [[UIView alloc] initWithFrame:CGRectMake(0, 0, APP_SCREEN_WIDTH, APP_SCREEN_HEIGHT)];
        tap.backgroundColor = RGBACOLOR(0, 0, 0, 0.5);
        tap.hidden = YES;
        tap.tag = 2013;
        UITapGestureRecognizer *tap1 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideContentView)];
        [tap addGestureRecognizer:tap1];
        [self.view addSubview:tap];
        [self.view addSubview:_replyContentView];
        
        CALayer *borderBottom = [CALayer layer];
        [borderBottom setBackgroundColor:[UIColor grayColor].CGColor];
        [borderBottom setFrame:CGRectMake(0, _replyContentView.height - 0.5, _replyContentView.width, 0.5)];
        [_replyContentView.layer addSublayer:borderBottom];
    }
    UIView *tapView = [self.view viewWithTag:2013];
    if(show){
        _textView.text = UDPostReplyCache;
        _replyContentView.hidden = NO;
        tapView.hidden = NO;
        [_textView becomeFirstResponder];
        if(_uploadImage || [UDPostReplyCache length]>5){
          [_postReply setEnabled:YES];
        }else{
          [_postReply setEnabled:NO];
        }
    }else {
        [_textView resignFirstResponder];
        [UIView animateWithDuration:0.2
                         animations:^{
                            //_replyContentView.transform = CGAffineTransformIdentity;
                             _replyContentView.top = APP_SCREEN_HEIGHT;
                        }
                         completion:^(BOOL finish){
                              _replyId = nil;
                              _replyFloor = nil;
                              _replyName.text = @"回复";
                              _replyContentView.hidden = YES;
                              tapView.hidden = YES;
                         }];
    }
}

//回复隐藏
- (void)hideContentView {
    [self showContentView:NO];
    _replyImage.image=Nil;
    _uploadImage=nil;
    [UIView animateWithDuration:0.2f
                          delay:0
                        options:UIViewAnimationOptionCurveEaseInOut
                     animations:^(void){
                         _emotionView.top = APP_SCREEN_HEIGHT;
                     }
                     completion:^(BOOL finished){
                         [self changeEmotionButton:NO];
                     }];
}

//修改表情按钮状态
- (void)changeEmotionButton:(BOOL)isShow
{
    if (!isShow) {
        [_emotionButton setImage:[UIImage imageNamed:@"pub_btn_emoji"] forState:UIControlStateNormal];
        [_emotionButton setTag:1];
    }else {
        [_emotionButton setImage:[UIImage imageNamed:@"pub_btn_keyboard"] forState:UIControlStateNormal];
        [_emotionButton setTag:2];
    }
}



- (void)scrollToReply
{
    if (_data.count >= 3) {
        [_tableView setContentOffset:CGPointMake(0, _tableView.tableHeaderView.height - 40) animated:YES];
    }else {
        [_tableView setContentOffset:CGPointMake(0, _tableView.contentSize.height - _tableView.height) animated:YES];
    }
}

#pragma mark UIScrollViewDelegate

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
  
}

#pragma mark - NOTIFICATION_CENTER
- (void)keyboardWillShow:(NSNotification *)notification
{
    NSValue *keyboardValue = [notification.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect frame = [keyboardValue CGRectValue];

    [UIView animateWithDuration:1.5f
                          delay:0
                        options:UIViewAnimationOptionCurveEaseInOut
                     animations:^(void){
                         _replyContentView.top = APP_SCREEN_HEIGHT-64-frame.size.height-TextViewHeight;
                     }
                     completion:^(BOOL finished){
                     }];
}

- (void)keyboardWillHide:(NSNotification *)notification
{
    if (_replyButtonClickType == 0) {
        [self hideContentView];
    }
    _replyButtonClickType = 0;
}

#pragma mark - UITextViewDelegate
- (void)textViewDidChange:(UITextView *)textView
{
    if(_textView.text.length > 1 || _uploadImage){
        _postReply.enabled = YES;
    }else{
        _postReply.enabled = NO;
    }

    if(_textView.text.length>10){
        [USER_DEFAULT setObject:_textView.text forKey:UDPostReplyCacheIdentify];
    }else{
      [USER_DEFAULT setObject:@"" forKey:UDPostReplyCacheIdentify];
    }
    [USER_DEFAULT synchronize];
}

#pragma mark - IndicatorDelegate

- (void)indicatorRefreshData
{
    [self _initData];
}

#pragma mark - Action

- (void)backPage:(id)button
{
    if(_isPost){
        NSInteger num = [self.navigationController.viewControllers count]-3;
        [self.navigationController popToViewController:self.navigationController.viewControllers[num] animated:YES];
    }else {
        [self.navigationController popViewControllerAnimated:YES];
    }
}

//显示大图
-(void)showImages:(UITapGestureRecognizer *)tap{
    UIView *view = [tap view];
    NSInteger i = view.tag - 100;
    
    if(_browser == nil) {
        _browser = [[MWPhotoBrowser alloc] initWithDelegate:self];
        _browser.displayActionButton = NO;
        _browser.displayNavArrows = YES;
        _browser.enableGrid = NO;
        
    }
    
    [_browser setCurrentPhotoIndex:i];
    UINavigationController *nc = [[UINavigationController alloc] initWithRootViewController:_browser];
    nc.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
    [self presentViewController:nc animated:YES completion:nil];
}


//回帖选择图片
-(void)selectImageFromPhone{
    _replyButtonClickType = 1;
    _replyImage.image=[UIImage imageNamed:@"camara_little"];
    _uploadImage=nil;

    if(_textView.text.length > 1){
        _postReply.enabled = YES;
    }else{
        _postReply.enabled = NO;
    }

    UIActionSheet *sheet =[[UIActionSheet alloc] initWithTitle:@"选择图片" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"相册",@"拍照", nil];

    [sheet showInView:self.view];
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    UIImagePickerController *pick =[[UIImagePickerController alloc] init];
    pick.delegate=self;

    if(buttonIndex==0){
        pick.sourceType=UIImagePickerControllerSourceTypePhotoLibrary;
        [self presentViewController:pick animated:YES completion:nil];
    }else if(buttonIndex==1){
        pick.sourceType= UIImagePickerControllerSourceTypeCamera;
        [self presentViewController:pick animated:YES completion:nil];
    }
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    UIImage *image = [info objectForKey: @"UIImagePickerControllerOriginalImage"];

    if (image.imageOrientation != UIImageOrientationUp){
        UIGraphicsBeginImageContextWithOptions(image.size, NO, image.scale);
        [image drawInRect:(CGRect){0, 0, image.size}];
        UIImage *normalizedImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        image=normalizedImage;
    }

    _replyImage.image = image;
    _uploadImage = image;
    _postReply.enabled = YES;
    [self dismissViewControllerAnimated:YES completion:nil];
    [_textFiled becomeFirstResponder];
}


- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
  [self dismissViewControllerAnimated:YES completion:nil];
  [_textFiled becomeFirstResponder];
}



//删除帖子
-(void)deletePost{
    NSDictionary *params;
    params = @{
             @"id":_pid,
             @"uid":@([[UserDao getInstance]getUserId]),
             @"puid":_contentData[@"user_id"]
             };

    [[AFAppClient sharedManager] getWithURL:@"" withParameters:params success:self.blockDeletePostSuccess failure:nil];
}


- (BOOL)canDelete
{
    if(_HomeUserInfo.userId ==[[NSString stringWithFormat:@"%@", _contentData[@"user_id"]]integerValue]){
        return YES;
    }
    
   
    return NO;
}



- (void)refreshReplyNum
{
    NSString *num = [NSString stringWithFormat:@"%@", _contentData[@"replynum"]];
    NSInteger count = [num integerValue] + 1;
    
    UILabel *replyNum = (UILabel *)[_headView viewWithTag:106];
    [replyNum setText:[NSString stringWithFormat:@"%ld", (long)count]];
}



- (void)postReply {
    
    if(![[Config Instance]isCookie]){
        MyloginViewController *login = [MyloginViewController shareController];
        
        UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:login];
        [self presentViewController:nav animated:YES completion:^{
            
        }];
    }else{
        
    NSString *text = _textFiled.text;

    NSDictionary *tmp = @{@"uid":@([[Config Instance]getUID]),
                          @"content":text,
                          @"postid":_msgId
                          };
    NSMutableDictionary *params = [NSMutableDictionary dictionaryWithDictionary:tmp];
    if(_replyId) {
        [params setObject:_replyId forKey:@"rereply_id"];
    }
    if(_uploadImage){
        [params setObject:_uploadImage forKey:@"pic0"];
    }
    
    //清除回复缓存
    [USER_DEFAULT setObject:@"" forKey:UDPostReplyCacheIdentify];
    if ([text length]==0) {
        [self ShowExclaHud:@"请输入内容"];
    }else{
       // [self hideContentView];
        [_textFiled resignFirstResponder];
        
        [[AFAppClient sharedManager] postWithURL:[NSString stringWithFormat:@"%@%@",SERVER_URL_NEW,API_USER_COMMENT_ARTICLE] withParameters:params success:self.blockPubReplySuccess failure:nil];
        [self showHud:@"回复中" isDim:NO];
        
        _uploadImage = nil;
        _textFiled.text = @"";
        _replyImage.image = [UIImage imageNamed:@"camara_little"];
    }
    
    if (_noReplyTip) {
        [_noReplyTip setHidden:YES];
    }
    }
}

//#pragma mark - MBProgressHUD
//- (void)ShowExclaHud:(NSString *)title{
//    if(_hud == nil) {
//        _hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
//    }
//    [self showHudComplete:title success:NO];
//}
//
//- (void)showHudComplete:(NSString *)title success:(BOOL)success {
//    NSString *name = success ? @"success" : @"excla";
//    _hud.dimBackground = NO;
//    _hud.customView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:name]];
//    _hud.mode = MBProgressHUDModeCustomView;
//    if(title.length > 0) {
//        _hud.labelText = title;
//    }
//    [_hud performSelector:@selector(removeFromSuperview) withObject:nil afterDelay:2];
//}
//
//- (void)showHud:(NSString *)title isDim:(BOOL)isDim {
//    _hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
//    _hud.dimBackground = isDim;
//    if(title.length > 0) {
//        _hud.labelText = title;
//    }
//}

- (void)hideModelView
{
    [self dismissViewControllerAnimated:NO completion:nil];
}



@end
